<template>
  <p-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <!-- //车间 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="车间">
              <p-select
                option-filter-prop="children"
                :filter-option="filterOption"
                v-model="active.workroomname"
                :value="active.workroomno"
              >
                <p-select-option
                  @click="QueryData(value)"
                  :key="value.workroomno"
                  :value="value.workroomname"
                  v-for="value in userlist"
                  >{{ value.workroomname }}</p-select-option
                >
              </p-select>
            </p-form-item>
          </p-col>
          <!-- 线体下拉输入框 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="线体">
              <p-select placeholder="请选择" v-model="activeList.linename">
                <!-- 遍历下拉选择框选项 -->
                <p-select-option
                  @click="QueryList(item)"
                  v-for="item in list"
                  :value="item.linename"
                  :key="item.lineno"
                  >{{ item.linename }}</p-select-option
                >
              </p-select>
            </p-form-item>
          </p-col>
          <!-- 排班状态 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="排班状态">
              <p-select placeholder="请选择" v-model="changeStateValue.text">
                <!-- 遍历下拉选择框选项 -->
                <p-select-option
                  @click="changeState(item)"
                  v-for="item in state"
                  :value="item.text"
                  :key="item.lineno"
                  >{{ item.text }}</p-select-option
                >
              </p-select>
            </p-form-item>
          </p-col>

          <!-- 排班日期选择框 -->
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="排班日期">
              <p-date-picker @change="onChange" />
            </p-form-item>
          </p-col>

          <!-- 查询输入框 -->
          <template>
            <p-col :xl="6" :lg="7" :md="8" :sm="24">
              <p-form-item label="搜索">
                <p-input-search
                  placeholder="请输入"
                  v-model="queryParam.filedName"
                ></p-input-search>
              </p-form-item>
            </p-col>
          </template>

          <!-- 展开收起 -->
          <p-col :xl="12" :lg="12" :md="12" :sm="24">
            
            <!-- 操作按钮区域 icon="plus"属性表示在按钮前置图标-->
            <div class="table-operator">
              <p-button type="primary" @click="searchQuery" icon="search"
              >查询</p-button
            >
              <!-- 排班规则按钮 -->
              <p-button type="primary" @click="handleSchedulingRules"
                >排班规则</p-button
              >
              <!-- 人员借调按钮 -->
              <p-dropdown :placement="placement">
                <p-button type="primary">人员借调</p-button>
                <p-menu slot="overlay">
                  <p-menu-item>
                    <a @click="handleTheSurplusOfHuman">富余人力</a>
                  </p-menu-item>
                  <p-menu-item>
                    <a @click="handleStaffSecondment">人员借调</a>
                  </p-menu-item>
                  <p-menu-item>
                    <a @click="handleDetailsOnSecondment">借调详情</a>
                  </p-menu-item>
                </p-menu>
              </p-dropdown>
              <!-- 生产排班发布 -->
              <p-dropdown :placement="placement">
                <p-button
                  type="primary"
                  @click="handleProductionScheduleRelease"
                  >生产排班发布</p-button
                >
              </p-dropdown>
              <!-- 高级查询按钮-->
              <j-super-query
                :fieldList="fieldList"
                ref="superQueryModal"
                @handleSuperQuery="handleSuperQuery"
              ></j-super-query>
            </div>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div>
      <!-- 导入导出功能栏 -->
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float: right">
          <a @click="handleExportXls('生产排班')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a> <p-icon type="import" />导入 </a>
          </p-upload>
          <p-divider type="vertical" />
          <a @click="this.active.lineno()"> <p-icon type="sync" />刷新 </a>
          <p-divider type="vertical" />
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template
                      v-if="
                        item.key != 'rowIndex' && item.dataIndex != 'action'
                      "
                    >
                      <p-col :span="12" v-bind:key="index">
                        <p-checkbox :value="item.dataIndex">{{
                          item.title
                        }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a> <p-icon type="setting" />自定义列 </a>
          </p-popover>
        </span>
      </div>

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChangeRow,
          type: 'radio',
        }"
        :customRow="clickThenSelect"
        @change="handleTableChange"
      >
        <!-- 差额 -->
        <template slot="layoutBalance" slot-scope="text">
          <a @click="handleSchedulingAdjustment">{{ text }}</a>
        </template>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic"
            >无此图片</span
          >
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt="图片不存在"
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic"
            >无此文件</span
          >
          <p-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)"
            >下载</p-button
          >
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
        </span>
      </p-table>
    </div>
    <p-modal ref="handeleAlert" title="提示" v-model="missingViseit" :confirmLoading="qlbtnLoad" @ok="missingSubmit">
      <p>排班人员不足，是否进行缺员排班？</p>
    </p-modal>

    <mesMfProductionLayout-modal
      ref="modalForm"
      :EnhanceJS="EnhanceJS"
      @ok="modalFormOk"
    ></mesMfProductionLayout-modal>
    <!-- 弹出窗 -->
    <Fx-compontens-modal
      @ok="modalFormOk"
      ref="modalCompon"
      :getList="queryInfo"
      :title="title"
      :dictOptions="dictOptions"
    ></Fx-compontens-modal>
    <!-- 富余人力弹出对话框 -->
    <div>
      <p-modal
        v-model="humanMainTenanceVisible"
        title="富余人力维护"
        :footer="null"
        width="50%"
      >
        <MesMfHumanMainTenancet
          ref="list"
          :linenoCode="linenoCode"
          :selectData="selectData"
        ></MesMfHumanMainTenancet>
      </p-modal>
    </div>
    <!-- 人员借调弹出对话框 -->
    <div>
      <p-modal v-model="staffSecondMentVisible" title="人员借调" width="800px">
        <MesMfStaffSecondMent
          ref="RefreshData"
          destroyOnClose="true"
        ></MesMfStaffSecondMent>
        <template slot="footer">
          <p-button key="back" @click="handleCancel">取消</p-button>
          <p-button
            key="submit"
            type="primary"
            :loading="loading"
            @click="handleOk"
            >确认</p-button
          >
        </template>
      </p-modal>
    </div>
    <!-- 借调详情弹出对话框 -->
    <div>
      <p-modal
        v-model="detailsOnSecondmentVisible"
        title="借调详情"
        width="70%"
      >
        <MesMfDetailsOnSecondment
          ref="data"
          :userlist="userlist"
        ></MesMfDetailsOnSecondment>
        <template slot="footer">
          <p-button key="back" @click="handleCancelDetails">取消</p-button>
          <p-button
            key="submit"
            type="primary"
            :loading="loading"
            @click="handleOkDetails"
            >确认</p-button
          >
        </template>
      </p-modal>
    </div>
    <!-- 排班调整弹出对话框 -->
    <div>
      <p-modal
        v-model="schedulingAdjustmentVisible"
        title="可用人员详情"
        width="70%"
      >
        <MesMfDetailsOfAvailablePersonnel
          :peoList="peoList"
        ></MesMfDetailsOfAvailablePersonnel>
        <template slot="footer">
          <p-button key="back" @click="handleCancelschedulingAdjustment"
            >取消</p-button
          >
          <p-button
            key="submit"
            type="primary"
            :loading="loading"
            @click="handleOkschedulingAdjustment"
            >确认</p-button
          >
        </template>
      </p-modal>
    </div>
    <!-- 排班规则对话框 -->
    <p-modal
      width="80%"
      v-if="SchedulingRulesVisible"
      v-model="SchedulingRulesVisible"
      :footer="null"
      title
      ok-text="确认"
      cancel-text="取消"
    >
      <MesMfSchedulingRules></MesMfSchedulingRules>
    </p-modal>
    <!-- 编辑：生产排班清单对话框 -->
    <div>
      <p-modal v-model="schedulingListVisible" width="70%" :header="null">
        <MesMfGenerateASchedulingList
          :dataInfo="dataInfo"
          v-on:handeleChildData="getChildData"
        ></MesMfGenerateASchedulingList>
        <template slot="footer">
          <p-button key="back" @click="handleCancelList">取消</p-button>
          <p-button
            key="submit"
            type="primary"
            :loading="loading"
            @click="handleSave"
            >保存</p-button
          >
        </template>
      </p-modal>
    </div>
  </p-card>
</template>

<script>
import MesMfDetailsOfAvailablePersonnel from "@/components/Privately/MesMfDetailsOfAvailablePersonnel.vue";
import MesMfDetailsOnSecondment from "@/components/Privately/MesMfDetailsOnSecondment.vue";
import MesMfStaffSecondMent from "@/components/Privately/MesMfStaffSecondment.vue";
import MesMfGenerateASchedulingList from "@/components/Privately/MesMfGenerateASchedulingList.vue";
import moment from "moment";
import MesMfSchedulingRules from "@/components/Privately/MesMfSchedulingRules.vue";
import MesMfHumanMainTenancet from "@/components/Privately/MesMfHumanMainTenancet.vue";
import MesMfProductionLayoutModal from "./modules/MesMfProductionLayoutModal";
import MesMfSchedulingDetailsList from "./MesMfSchedulingDetailsList";
import JDictSelectTag from "@/components/dict/JDictSelectTag.vue";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { api } from "@/api/manage";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj } from "@/utils/util";
import Vue from "vue";
import JDate from "@/components/jeecg/JDate.vue";
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction, putAction } from "@/api/manage";
import { ajaxGetDictItems } from "@/api/api";
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";

//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "layoutTime",
    text: "排班日期",
    type: "string",
  },
  {
    value: "layoutClasses",
    text: "班次",
    type: "select",
    dictCode: "mes_layout_classes",
  },
  {
    value: "layoutState",
    text: "排班状态",
    type: "select",
    dictCode: "mes_layout_state",
  },
  // {
  //   value: "layoutGroup",
  //   text: "班组",
  //   type: "string",
  // },
  {
    value: "lineno",
    text: "线体编码",
    type: "string",
  },
  {
    value: "linename",
    text: "线体名称",
    type: "string",
  },
  {
    value: "layoutManpower",
    text: "人力需求",
    type: "int",
  },
  // {
  //   value: "layoutBethe",
  //   text: "在职人数",
  //   type: "int",
  // },
  {
    value: "layoutSteak",
    text: "排配人数",
    type: "int",
  },
  {
    value: "layoutTrue",
    text: "实到人数",
    type: "int",
  },
  {
    value: "layoutBorrow",
    text: "借用人数",
    type: "int",
  },
  {
    value: "layoutBalance",
    text: "排配差额",
    type: "BigDecimal",
  },
  // {
  //   value: "createBy",
  //   text: "创建人",
  //   type: "string",
  // },
  {
    value: "createTime",
    text: "创建日期",
    type: "Date",
  },
  {
    value: "updateBy",
    text: "更新人",
    type: "string",
  },
  {
    value: "updateTime",
    text: "更新日期",
    type: "Date",
  },
  {
    value: "remark",
    text: "备注",
    type: "string",
  },
];

export default {
  name: "MesMfProductionFound",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    JDate,
    FxCompontensModal,
    MesMfProductionLayoutModal,
    JDictSelectTag,
    MesMfHumanMainTenancet,
    MesMfSchedulingRules,
    MesMfGenerateASchedulingList,
    MesMfStaffSecondMent,
    MesMfDetailsOnSecondment,
    MesMfDetailsOfAvailablePersonnel,
  },

  data() {
    return {
      qlbtnLoad:false,
      changeStateValue:{},
      state: [],
      //默认车间
      active: {},
      list: [],
      //默认线体
      activeList: {},
      // 线体列表
      userlist: [],
      selectData: {},
      tableSelection: {},
      sentData: {},
      //保存表单参数
      mfSchedulingDetailsEditParams: {
        detailsDemand: "",
        detailsDrilling: "",
        detailsHaverowtime: "",
        detailsManpower: "",
        detailsOutputtime: "",
        detailsSign: "",
        detailsSteakwith: "",
        elements: {
          detailsDemand: "",
          detailsDrilling: "",
          detailsHaverowtime: "",
          detailsManpower: "",
          detailsOutputtime: "",
          detailsSign: "",
          detailsSteakwith: "",
          elements: "",
          empname: "",
          empno: "",
          empsex: "",
          id: "",
          processTwocode: "",
          processTwoname: "",
          productLayoutId: "",
          skillcode: "",
          skillname: "",
          telephone: "",
          workstationCode: "",
          workstationName: "",
          empname: "",
          empno: "",
          empsex: "",
          id: "",
          processTwocode: "",
          processTwoname: "",
          productLayoutId: "",
          skillcode: "",
          skillname: "",
          telephone: "",
          workstationCode: "",
          workstationName: "",
        },
      },
      //参数
      infoQuery: [],
      //线体列表
      linenoList: [],
      //排班调整
      schedulingAdjustmentVisible: false,
      //借调详情
      detailsOnSecondmentVisible: false,
      //排班清单
      schedulingListVisible: false,
      //日期
      moment,
      //人员借调
      staffSecondMentVisible: false,
      //排班规格
      SchedulingRulesVisible: false,
      //富余人力
      humanMainTenanceVisible: false,
      //缺员排班发布提示弹窗
      missingViseit:false,
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      superQueryParams: "",
      EnhanceJS: "",
      cgButtonLinkList: [],
      cgButtonList: [],
      title: "", //存表名
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "id",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "生产工单",
          align: "center",
          dataIndex: "productionno",
          key: "productionno  ",
        },
        {
          title: "工序工单",
          align: "center",
          dataIndex: "processbillno",
          key: "processbillno",
        },

        {
          title: "班次",
          align: "center",
          dataIndex: "classtimename",
          key: "classtimename",
        },
        {
          title: "排班状态",
          align: "center",
          dataIndex: "layoutState",
          key: "layoutState",
          customRender: function (t) {
            if (t == "1") {
              return "已排班";
            } else if (t == "0") {
              return "未排班";
            } else if (t == "2") {
              return "已发布";
            }
          },
          // width: "15%",
        },
        // {
        //   title: "班组",
        //   align: "center",
        //   dataIndex: "layoutGroup",
        //   key: "layoutGroup",
        //   scopedSlots: { customRender: "layoutGroup" },
        //   // width: "15%",
        // },
        {
          title: "车间编码",
          align: "center",
          dataIndex: "workroomno",
          key: "workroomno",
        },
        {
          title: "车间名称",
          align: "center",
          dataIndex: "workroomname",
          key: "workroomname",
        },
        {
          title: "线体编码",
          align: "center",
          dataIndex: "lineno",
          key: "lineno",
        },
        {
          title: "线体名称",
          align: "center",
          dataIndex: "linename",
          key: "linename",
        },
        {
          title: "人力需求",
          align: "center",
          dataIndex: "layoutManpower",
          key: "layoutManpower",
          scopedSlots: { customRender: "layoutManpower" },
          // width: "15%",
        },
        // {
        //   title: "在职人数",
        //   align: "center",
        //   dataIndex: "layoutBethe",
        //   key: "layoutBethe",
        //   scopedSlots: { customRender: "layoutBethe" },
        //   // width: "15%",
        // },
        {
          title: "排配人数",
          align: "center",
          dataIndex: "layoutSteak",
          key: "layoutSteak",
          scopedSlots: { customRender: "layoutSteak" },
          // width: "15%",
        },
        {
          title: "实到人数",
          align: "center",
          dataIndex: "layoutTrue",
          key: "layoutTrue",
          scopedSlots: { customRender: "layoutTrue" },
          // width: "15%",
        },
        {
          title: "借用人数",
          align: "center",
          dataIndex: "layoutBorrow",
          key: "layoutBorrow",
          scopedSlots: { customRender: "layoutBorrow" },
          // width: "15%",
        },
        {
          title: "排配差额",
          align: "center",
          dataIndex: "layoutBalance",
          key: "layoutBalance",
          scopedSlots: { customRender: "layoutBalance" },
          // width: "15%",
        },
        {
          title: "实到差额",
          align: "center",
          dataIndex: "",
          // width: "15%",
        },
        {
          title: "可用人力",
          align: "center",
          dataIndex: "detailsManpower",
          key: "code",
          scopedSlots: { customRender: "encodingRules" },
          // width: "15%",
        },
        // {
        //   title: "标准产出工时",
        //   align: "center",
        //   dataIndex: "detailsOutputtime",
        //   key: "code",
        //   scopedSlots: { customRender: "encodingRules" },
        //   // width: "15%",
        // },
        // {
        //   title: "岗位标记",
        //   align: "center",
        //   dataIndex: "detailsSign",
        //   key: "code",
        //   scopedSlots: { customRender: "encodingRules" },
        //   // width: "15%",
        // },

        // {
        //   title: "性别",
        //   align: "center",
        //   dataIndex: "empsex",
        //   key: "code",
        //   scopedSlots: { customRender: "encodingRules" },
        //   // width: "15%",
        // },

        // {
        //   title: "工站编码",
        //   align: "center",
        //   dataIndex: "workstationCode",
        //   key: "code",
        //   scopedSlots: { customRender: "encodingRules" },
        //   // width: "15%",
        // },
        // {
        //   title: "工站名称",
        //   align: "center",
        //   dataIndex: "workstationName",
        //   key: "code",
        //   scopedSlots: { customRender: "encodingRules" },
        //   // width: "15%",
        // },

        // {
        //   title: "数量单位",
        //   align: "center",
        //   dataIndex: "unit",
        //   key: "code",
        //   scopedSlots: { customRender: "encodingRules" },
        //   // width: "15%",
        // },
        {
          title: "排产数量",
          align: "center",
          dataIndex: "quantity",
          key: "quantity",
          scopedSlots: { customRender: "quantity" },
          // width: "15%",
        },
        {
          title: "排班单号",
          align: "center",
          dataIndex: "schedulingOrder",
          key: "schedulingOrder",
          scopedSlots: { customRender: "schedulingOrder" },
          // width: "15%",
        },
        {
          title: "产品编码",
          align: "center",
          dataIndex: "productcode",
          key: "productcode",
          scopedSlots: { customRender: "productcode" },
          // width: "15%",
        },
        {
          title: "产品描述",
          align: "center",
          dataIndex: "productcode",
          key: "productcode",
          scopedSlots: { customRender: "productcode" },
          // width: "15%",
        },
        // {
        //   title: "总数",
        //   align: "center",
        //   dataIndex: "total",
        //   key: "code",
        //   scopedSlots: { customRender: "encodingRules" },
        //   // width: "15%",
        // },

        {
          title: "	排班日期",
          align: "center",
          dataIndex: "layoutTime",
          key: "code",
          scopedSlots: { customRender: "encodingRules" },
          customRender: function (t) {
            let now = new Date(t);
            let year = now.getFullYear(); //取得4位数的年份
            let month = now.getMonth() + 1; //取得日期中的月份，其中0表示1月，11表示12月
            let date = now.getDate(); //返回日期月份中的天数（1到31）
            return year + "-" + month + "-" + date;
          },
          // width: "15%",
        },
        {
          title: "操作",
          align: "center",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          key: "action",
          // width: "15%",
        },
      ],
      //获取生产排班清单ROW信息
      dataInfo: {},
      url: {
        //获取当前用户信息
        userUid: "/mes-manpower/mesHrEmployeeinfo/currUser",
        //新增或者更新排班详情(排班调整或可用人员详情 保存)
        saveScheduling: "/mes-manufacture/mfSchedulingDetails",
        //排班发布
        schedulingRelease: "/mes-manufacture/mfProductionLayout/distribute",
        // 缺员排班发布
        lackRelease: "/mes-manufacture/mfProductionLayout/force/distribute",
        //获取当前用户信息
        currentUserUid: "/mes-manpower/mesHrEmployeeinfo/currUser",
        //分页获取生产排班列表
        list: "/mes-manufacture/mfProductionLayout/list",
        delete: "/mes-manufacture/auto/mesMfProductionLayout/delete",
        deleteBatch: "/mes-manufacture/auto/mesMfProductionLayout/deleteBatch",
        exportXlsUrl: "/mes-manufacture/auto/mesMfProductionLayout/exportXls",
        importExcelUrl:
          "/mes-manufacture/auto/mesMfProductionLayout/importExcel",
        getColumns: "/mes-manufacture/online/cgform/api/getColumns/",
        buttonAction: "/mes-manufacture/online/cgform/api/doButton",
      },
      dictOptions: {
        layoutClasses: [],
        layoutState: [],
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      query: {
        lineno: "",
      },
      selectedMainId: "",
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
    newSelectedMainId: function () {
      if (typeof this.selectedMainId == "number") {
        return this.selectedMainId.toString();
      } else {
        return this.selectedMainId;
      }
    },
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
  },

  created() {
    // this.linenoData();
    this.initButtonList();
    this.initColumns();
    this.setdefColumns();
    //初始化分页获取生产排班列表
    //获取当前用户
    this.getuserUidList();
    this.loadState();
  },
  mounted() {
    //用$on事件来接收参数
    this.evBus.$on("receive", (data) => {});
  },
  methods: {
    // 获取子组件传过来的参数
    getChildData(data) {
      this.sentData = data;
    },

    //uid 用户
    getuserUidList() {
      getAction(this.url.currentUserUid, { sysCode: "mes" }).then((res) => {
        if (res.success) {
          // this.$message.success(res.msg);
          this.userInfo = res.data;
          this.selectData = res.data;
          this.loadWorkroomno(res.data);
          this.loadData();
        }
        if (res.code === 510) {
          this.$message.warning();
        }
      });
    },
    // 根据用户信息加载车间
    loadWorkroomno(data) {
      this.userlist = this.getWorkrooms(data);
      this.linenoCode = this.getWorkrooms(data);
      this.active = this.getWorkrooms(data)[0];
      this.list = this.active.lines;
      this.activeList = this.active.lines[0];
    },
    // 选择车间,拉取线体
    QueryData(data) {
      this.active = data;
      this.list = data.lines;
      this.activeList = data.lines[0];
    },
    QueryList(data) {
      this.activeList = data;
    },
    // 处理车间数据函数
    getWorkrooms(auth) {
      var dutyDtos = auth.dutyDtos;
      var workroomnos = new Array();
      for (var i = 0; i < dutyDtos.length; i++) {
        var temp = dutyDtos[i];
        var elment = this.getWorkroomItem(workroomnos, temp.workroomno);
        if (elment == null) {
          elment = {
            workroomno: temp.workroomno,
            workroomname: temp.workroomname,
            lines: new Array(),
          };
          workroomnos.push(elment);
        }
        var lineElement = {
          lineno: temp.lineno,
          linename: temp.linename,
          classno: temp.classno,
          classname: temp.classname,
        };
        elment.lines.push(lineElement);
      }
      return workroomnos;
    },
    // 处理车间数据函数
    getWorkroomItem(workroomnos, workroomno) {
      var result = null;
      for (var i = 0; i < workroomnos.length; i++) {
        var item = workroomnos[i];
        if (workroomno === item.workroomno) {
          result = item;
          break;
        }
      }
      return result;
    },

    //选中项发生变化时的回调
    onSelectChangeRow(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0];
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      this.tableSelection = selectionRows[0];
    },
    // 缺员排班发布
    missingSubmit(){
      this.qlbtnLoad=true
        putAction(this.url.lackRelease, {
          ids: [this.selectedMainId],
        }).then((res) => {
          if (res.success) {
            this.$message.success("缺员排班发布成功");
            this.loadData();
            this.qlbtnLoad=false
            this.missingViseit=false
          }
          if (res.code === 510) {
            this.$message.warning(res.msg);
          }
        });
    },

    //生产排班发布
    handleProductionScheduleRelease() {
      // 判断是否选中你
      if (this.selectionRows.length > 0) {
        let layoutSteak = this.selectionRows[0].layoutSteak;
        let layoutManpower = this.selectionRows[0].layoutManpower;
        // 判断是否已排班
        console.log(this.selectionRows[0].layoutState);
        if (this.selectionRows[0].layoutState != 2) {
          if(this.selectionRows[0].layoutState==0){
            this.$message.warning('请先排班')
          }else{
            if (layoutSteak == layoutManpower) {
            putAction(this.url.schedulingRelease, {
              ids: [this.selectedMainId],
            }).then((res) => {
              if (res.success) {
                this.$message.success("发布成功");
                this.loadData();
              }
              if (res.code === 510) {
                this.$message.warning(res.msg);
              }
            });
          } else {
            this.missingViseit=true
          }
          }
          
        } else {
          this.$message.warning("该工单已发布!");
        }
      } else {
        this.$message.warning("请选择生产排版！");
      }
    },
    //线体下拉框改变event
    // handleChangeLineno(val) {
    //   this.infoQuery = {
    //    lineno:this.active.lineno,
    //    workroomno:this.active.workroomno
    //   };
    //   getAction(this.url.list, this.infoQuery).then((res) => {
    //     if (res.success) {
    //       // this.$message.success(res.msg);
    //       this.dataSource = res.data.records;
    //     }
    //     if (res.code === 510) {
    //       this.$message.warning(res.msg);
    //     }
    //   });
    // },
    //线体选择下拉框
    // linenoData() {
    //   getAction(this.url.currentUserUid, { sysCode: "mes" }).then((res) => {
    //     if (res.success) {
    //       // this.$message.success("线体选择成功");
    //       this.linenoList.push(res.data);
    //     }
    //     if (res.code === 510) {
    //       this.$message.warning("线体选择失败");
    //     }
    //   });
    // },
    setdefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1;
        this.columns.forEach((item, index) => {
          item["width"] = 130;
        });
        this.columns[arrLength]["fixed"] = "right";
      }
    },
    handleEdit(row) {
      this.dataInfo = {
        id: row.id,
        processbillno: row.processbillno,
      };
      this.schedulingListVisible = true;
    },
    changeState(data){
      this.changeStateValue=data
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },
    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.active.lineno();
    },
    // 获取查询条件
    getQueryParams() {
      let sqp = {};
      if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },
    initDictConfig() {
      initDictOptions("mes_layout_classes").then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, "layoutClasses", res.data);
        }
      });
      initDictOptions("mes_layout_state").then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, "layoutState", res.data);
        }
      });
    },
    // clickThenSelect(record) {
    //   return {
    //     on: {
    //       click: () => {
    //         this.onSelectChange(record.id.split(","), [record]);
    //       },
    //     },
    //   };
    // },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.selectedMainId = "";
    },
    // onSelectChange(selectedRowKeys, selectionRows) {
    //   this.selectedMainId = selectedRowKeys[0];
    //   this.selectedRowKeys = selectedRowKeys;
    //   this.selectionRows = selectionRows;
    // },
    //分页获取生产排班列表API请求参数
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!");
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.onClearSelected();
      var params = this.getQueryParams(); //查询条件
      var myDate = new Date();
      myDate.getFullYear(); //获取完整的年份(4位,1970-????)
      myDate.getMonth(); //获取当前月份(0-11,0代表1月)
      myDate.getDate(); //获取当前日(1-31)
      let nowData;
      if (this.query.layoutTime) {
        nowData = this.query.layoutTime;
      } else {
        nowData =
          myDate.getFullYear() +
          "-" +
          (myDate.getMonth() + 1) +
          "-" +
          myDate.getDate();
      }

      this.loading = true;
      let newQuery = {
        layoutTime: nowData,
        lineno: this.activeList.lineno,
        workroomno: this.active.workroomno,
        keyword: this.queryParam.filedName,
        layoutState:this.changeStateValue.value
      };
      getAction(this.url.list, newQuery).then((res) => {
        if (res.success) {
          //get请求成功，把数据列表赋值给Table数据源
          this.dataSource = res.data.records || [];
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },

    // 弹出窗组件
    showDemoModal() {
      this.$refs.modalCompon.modalShow();
    },
    // 点击btn获取数据
    btnGetData(tableName, title) {
      getAction(`${this.url.getColumns}`, {
        tableName: tableName,
      }).then((res) => {
        if (res.code == 0) {
          this.queryInfo = res.data.columns;
          this.title = title;
          this.dictOptions = res.data.dictOptions;
          this.showDemoModal();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    //筛选分组
    getGroupTag(arrList) {
      let arr = [];
      var map = {},
        dest = [];
      arrList.forEach((item, index) => {
        if (item.groupTag) {
          arr.push(item);
        }
      });
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.groupTag]) {
          dest.push({
            groupTag: ai.groupTag,
            name: ai.groupName,
            data: [ai],
          });
          map[ai.groupTag] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.groupTag == ai.groupTag) {
              dj.data.push(ai);
              break;
            }
          }
        }
      }
      this.groupTag = dest;
    },
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    initButtonList() {
      // getAction(`${this.url.getColumns}8ac49ec7733bce480173558966a8012d`).then(
      //   (res) => {
      //     console.log("--获取自定义按钮->>", res);
      //     if (res.success) {
      //       this.code = res.data.code;
      //       this.initCgButtonList(res.data.cgButtonList);
      //       this.initCgEnhanceJs(res.data.enhanceJs);
      //       this.getGroupTag(res.data.cgButtonList);
      //     } else {
      //       this.$message.warning(res.msg);
      //     }
      //   }
      // );
    },
    initCgEnhanceJs(enhanceJs) {
      //console.log("--onlineList-js增强",enhanceJs)
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        console.log("自定义按钮link请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },
    //控制排班规则对话框的隐藏与展示
    handleSchedulingRules() {
      this.SchedulingRulesVisible = true;
    },
    //控制富余人力对话框的隐藏与展示
    handleTheSurplusOfHuman() {
      if (this.$refs.list) {
        this.$refs.list.loadData();
      }
      this.humanMainTenanceVisible = true;
    },
    //人员借调
    handleStaffSecondment() {
      if (this.$refs.RefreshData) {
        this.$refs.RefreshData.initData();
        this.$refs.RefreshData.loadData();
      }
      this.staffSecondMentVisible = true;
    },
    //排班日期选择框
    onChange(val) {
      this.query.layoutTime = this.moment(val).format("YYYY-MM-DD");
    },
    //查询
    searchQuery() {
      this.loadData();
    },

    //排班清单取消按钮
    handleCancelList() {
      this.schedulingListVisible = false;
    },
    //排班清单保存按钮
    handleSave() {
      this.schedulingListVisible = false;
      const info = {
        productLayoutId: this.sentData.id,
        elements: this.sentData.data,
      };
      postAction(this.url.saveScheduling, info).then((res) => {
        if (res.success) {
          this.$message.success("保存生产排班详情成功");
          this.loadData();
        }
        if (res.code === 510) {
          this.$message.warning("保存生产排班详情失败");
        }
      });
    },

    //人员借调对话框取消按钮
    handleCancel() {
      this.loadData();
      this.staffSecondMentVisible = false;
    },
    //人员借调对话框确定按钮
    handleOk() {
      this.loadData();
      this.staffSecondMentVisible = false;
    },
    //借调详情点击事件
    handleDetailsOnSecondment() {
      if (this.$refs.data) {
        this.$refs.data.loadData();
      }
      this.detailsOnSecondmentVisible = true;
    },
    //借调详情取消按钮
    handleCancelDetails() {
      this.loadData();
      this.detailsOnSecondmentVisible = false;
    },
    //借调详情确定按钮
    handleOkDetails() {
      this.loadData();
      this.detailsOnSecondmentVisible = false;
    },
    //差额点击事件
    handleSchedulingAdjustment() {
      this.peoList = this.sentData;
      this.schedulingAdjustmentVisible = true;
    },
    //排班调整取消按钮
    handleCancelschedulingAdjustment() {
      this.schedulingAdjustmentVisible = false;
    },
    //排班调整确认
    handleOkschedulingAdjustment() {
      this.schedulingAdjustmentVisible = false;
    },
    // 排班状态字典
    loadState() {
      ajaxGetDictItems("mes_layout_state").then((res) => {
        if (res.code == 0) {
          this.state = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>
